package com.test;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.testDemo.utils.TestUtils;

/**
 * 根据接口列表生成div的方法
 * 
 * @author Administrator
 */
public class CreateDiv {

    public static Map<String, String> createDiv(String interfaceName) throws Exception {
        Map map = new HashMap<String, String>();
        List<String> interfaces = new ArrayList<String>();
        if (!TestUtils.isEmpty(interfaceName)) {
            interfaces.add(TestUtils.INTERFACE_EXCEL_PATH + interfaceName + ".xlsx");
        }
        else {
            interfaces = TestUtils.getExcelFilePath(TestUtils.INTERFACE_EXCEL_PATH);
        }
        for (String interfacePath : interfaces) {
            XSSFWorkbook work = new XSSFWorkbook(new FileInputStream(interfacePath));
            // 获取输出流
            PrintWriter pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(TestUtils.DIV_PATH
                    + "test.html", true)), true);
            // 获取接口规范所在的sheet页
            Sheet sheet = work.getSheet("HttpRest协议");
            Element msg = getRowContent(sheet);
            if (TestUtils.isEmpty(msg.getChildElements())) {
                System.err.println("接口:" + interfacePath + "生成模板失败,请查看");
                break;
            }
        }
        return map;
    }

    /**
     * 获取Excel的msg中每一行的信息
     * 
     * @param sheet
     * @return
     * @throws Exception
     */
    public static Element getRowContent(Sheet sheet) throws Exception {

        Element msg = new Element();
        msg.setElementName("msg");
        msg.setCheckType("Y");
        msg.setExplan("报文体");
        msg.setFatherNode(true);
        msg.setFatherNodeName("body");
        int startRowNum = -1;
        int endRowNum = -1;
        long start = System.currentTimeMillis();
        boolean isStart = false;
        ok: for (Row row : sheet) {
            for (Cell cell : row) {
                String cellContent = "";
                if (TestUtils.isEmpty(cell)) {
                    continue;
                }
                cell.setCellType(Cell.CELL_TYPE_STRING); // 设置单元格格式为String
                cellContent = cell.getStringCellValue();
                // 判断是否为读取范围的开始,在遇到第一个"msg"的下一行开始
                if (!isStart && TestUtils.CHECK_KEY.equals(cellContent)) {
                    startRowNum = row.getRowNum() + 1;
                    isStart = true;
                }
                if ("para".equals(cellContent)) {
                    endRowNum = row.getRowNum();
                    break ok;
                }
            }
        }
        long end = System.currentTimeMillis();
        System.out.println("用时:" + (end - start) + "\n开始行:" + startRowNum + "\n结束行:" + endRowNum);
        if (-1 != startRowNum) {
            Map ret = getChildElement(msg, sheet, startRowNum, endRowNum);
            msg = (Element) ret.get("element");
        }
        // 校验数据的正确性
        String elements = msg.getChildElements().toString();
        for (int i = startRowNum; i < endRowNum; i++) {
            Row row = sheet.getRow(i);
            Cell cell = row.getCell(1);
            String cellContent = "";
            if (TestUtils.isEmpty(cell)) {
                continue;
            }
            cell.setCellType(Cell.CELL_TYPE_STRING); // 设置单元格格式为String
            cellContent = cell.getStringCellValue();
            System.out.println("第" + (i + 1) + "行节点:[" + cellContent + "]正确性校验:");
            if (!elements.contains(cellContent)) {
                System.err.println("第" + (i + 1) + "行节点[" + cellContent + "]未拼装");
            }
        }
        // System.err.println("msg:");
        // System.out.println(msg.getChildElements());
        String htmlHead = "<!DOCTYPE html><html><head><title>生成的某个页面</title><meta http-equiv='content-type' content='text/html; charset=UTF-8'></head><body>";
        String htmlFoot = "</body></html>";
        System.out.println(htmlHead + msg.getHtmlContent() + htmlFoot);
        return msg;
    }

    /**
     * 该方法为递归方法,获取父节点下的所有子节点
     * 
     * @param fatherElement
     * @param sheet
     * @param startRowNum
     * @param endRowNum
     *            整个sheet页的最后一行
     */
    public static Map getChildElement(Element fatherElement, Sheet sheet, int startRowNum, int endRowNum) {
        int rowNum = startRowNum;
        // Element lastFatherElement = new Element();
        Element lastElement = new Element();
        ok: for (int i = startRowNum; i < endRowNum; i++) {
            rowNum = i;
            Row row = sheet.getRow(i);
            List<String> rowContent = new ArrayList<String>();
            for (int j = 1; j <= 5; j++) {
                Cell cell = row.getCell(j);
                String cellContent = "";
                if (TestUtils.isEmpty(cell)) {
                    continue;
                }
                cell.setCellType(Cell.CELL_TYPE_STRING); // 设置单元格格式为String
                cellContent = cell.getStringCellValue();
                // 塞默认空值
                rowContent.add(TestUtils.isEmpty(cellContent) ? "" : cellContent);
            }
            // 该行有内容,则放入
            if (!TestUtils.isEmpty(rowContent)) {
                if ("groupFlag".equals(rowContent.get(0)) && "phoneTemplate".equals(rowContent.get(1))) {
                    System.out.println("");
                }
                // 获取读取行的结束值,以读取到[para] 前有值的最后一行,同时,读取结束
                if (!TestUtils.isEmpty(rowContent.get(1)) && !fatherElement.getElementName().equals(rowContent.get(1))
                        && !rowContent.get(1).equals(
                                lastElement.getElementName())) {
                    break ok;
                }
                Element element = new Element(rowContent.get(0), rowContent.get(1), rowContent.get(2),
                        rowContent.get(3), rowContent.get(4), null);
                // 判断该节点是否是上一个元素的子节点
                if ("*,+".contains(element.getCheckType())) {
                    // 当前行为父元素行,调用方法为从下一行开始
                    element.setFatherNode(true);// 是父节点
                    Map ret = getChildElement(element, sheet, row.getRowNum() + 1, endRowNum);
                    element = (Element) ret.get("element");
                    i = (Integer) ret.get("rowNum") - 1;// 需要跟i++互相抵消,内层方法执行到的行数,下次循环应执行该行数
                }
                else if (element.getFatherNodeName().equals(lastElement.getElementName())) {
                    // 当前行为父元素下一行(子元素),调用方法为从当前行开始
                    lastElement.setFatherNode(true);// 是父节点
                    Map ret = getChildElement(lastElement, sheet, row.getRowNum(), endRowNum);
                    element = (Element) ret.get("element");
                    i = (Integer) ret.get("rowNum") - 1;// 需要跟i++互相抵消,内层方法执行到的行数,下次循环应执行该行数
                    // 去掉上次循环已经放入fatherElement中的该父元素
                    fatherElement.getChildElements().remove(fatherElement.getChildElements().size() - 1);
                }
                else {
                    lastElement = element;
                }
                // createHtmlNode(element);// 根据节点生成html内容
                fatherElement.getChildElements().add(element);
            }
        }
        Map retMap = new HashMap();
        fatherElement.setHtmlContent(createHtmlNode(fatherElement));
        retMap.put("element", fatherElement);
        retMap.put("rowNum", rowNum);// 外层的方法从当前行开始执行
        return retMap;
    }

    /**
     * 拼装每一个父节点的html内容
     * 
     * @param rows
     */
    public static String createHtmlNode(Element element) {
        String childHtml = "";
        if (!TestUtils.isEmpty(element.getChildElements())) {
            for (Element ele : element.getChildElements()) {
                childHtml += createHtmlNode(ele);
            }
        }
        String htmlContent = "";
        String checkType = element.getCheckType();
        String elementId = element.getElementName() + element.getFatherNodeName();
        if (element.isFatherNode()) {// 如果是父节点
            // htmlContent = "<div>";
            htmlContent += "Y,+".contains(checkType) ? "<h3 required='required'>" : "<h3>";// 优化：是否为空校验
                                                                                           // required="required"
                                                                                           // FIXME
            htmlContent += element.getElementName() + " " + element.getExplan().replace("\n", " ") + "</h3>";
            if ("+,*".contains(checkType)) { // list类型的父节点
                htmlContent += "<input id= '" + elementId + "' type='button' value='+' /> <br/>";
            }
            // htmlContent += "<table>" + childHtml + "</table>";// </div>";
            htmlContent += childHtml;
        }
        else {
            // 计算输入框的最大值
            String maxLength = element.getElementType();
            maxLength = TestUtils.isEmpty(maxLength) ? "" : "maxlength='"
                    + maxLength.substring(maxLength.indexOf("(") + 1,
                            maxLength.length() - 1) + "' ";
            htmlContent += "<td><label>" + element.getElementName() + ":</label></td> <td>";
            htmlContent += "Y".equals(checkType) ? "<input required='required' " : "<input ";// 优化：是否为空校验 FIXME
            htmlContent += "id= '" + elementId + "' type='text' placeholder='" + element.getExplan().replace("\n", " ")
                    + "' " + maxLength + "></td>";
            htmlContent = "<tr>" + htmlContent + childHtml + "</tr><br/>";
        }
        // htmlContent = htmlContent + "<br/>";
        element.setHtmlContent(htmlContent);
        return htmlContent;
    }

    public static void main(String[] args) {
        try {
            createDiv("ecaop.trades.sell.mob.oldu.product.chg（套餐服务变更）");
            // createDiv("ecaop.trades.sell.mix.newu.open.app（融合业务开户处理申请-修改版）");
        }
        catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
